package com.study.hot.architecture.mvx.mvp.view;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.study.hot.R;
import com.study.hot.architecture.mvx.mvp.presenter.JZQPresenter;


/**
 * <pre>
 *     author : slx
 *     time   : 2020/11/20
 *     desc   : 井字棋改为mvp架构
 * </pre>
 */
public class MvpJZQActivity extends AppCompatActivity implements JZQView {

    // 属于View的
    private GridLayout gridLayout;
    private TextView tvWinner;

    private JZQPresenter presenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jingziqi);
        gridLayout = findViewById(R.id.buttonViewGroup);
        tvWinner = findViewById(R.id.winnerTv);
        presenter = new JZQPresenter(this);
    }

    /**
     * item 点击下棋,此时view层只关心用户交互的View，而不关心具体逻辑
     *
     * @param view
     */
    public void onCellClicked(View view) {
        Button button = (Button) view;
        // 从tag属性中计算当前点击的行、列
        String btnTag = button.getTag().toString();
        int row = Integer.parseInt(btnTag.substring(0, 1));
        int col = Integer.parseInt(btnTag.substring(1, 2));
        presenter.onButtonSelected(row, col);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_jingziqi, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_reset:
                presenter.onRestartGame();
                return true;
            default:
                return super.onOptionsItemSelected(item);

        }
    }

    @Override
    public void clearWinnerDisplay() {
        tvWinner.setText("");
    }

    @Override
    public void clearButtonText() {
        int childCount = gridLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            ((Button) gridLayout.getChildAt(i)).setText("");
        }
    }

    @Override
    public void setButtonText(int row, int col, String text) {
        Button btn = gridLayout.findViewWithTag("" + row + col);
        btn.setText(text);
    }

    @Override
    public void showWinner(String winner) {
        tvWinner.setText(winner);
    }
}
